<template>
  <div>

    <el-row>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="del">删除</el-button>
      </el-col>
    </el-row>

    <el-button type="primary" size="mini" @click="openAdd"><i class="el-icon-plus">新增农作物</i></el-button>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="35">
      </el-table-column>
      <el-table-column
          prop="cropsId"
          label="作物编号">
      </el-table-column>
      <el-table-column
          prop="cropsName"
          label="作物名称">
      </el-table-column>
      <el-table-column
          prop="status"
          label="状态"
          show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0">种植中</el-tag>
          <el-tag type="danger" v-if="scope.row.status === 1">已出售</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100">
        <template slot-scope="scope">
          <el-button v-show="scope.row.status==0" size="mini" type="text" @click="zqlog(scope.row)">周期记录</el-button>
          <el-button @click="handleClick(scope.row)" size="mini" type="text">作物详情</el-button>
          <el-button @click="ProcesshandleClick(scope.row)" size="mini" type="text">过程详情</el-button>
          <el-button v-show="scope.row.status==0" size="mini" type="text" @click="tzys(scope.row)">通知运输</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--    新增作物-->
    <el-dialog title="记录作物" :visible.sync="dialogFormVisible">
      <el-form :model="addForm">
        <el-form-item label="作物名称" :label-width="formLabelWidth">
          <el-input v-model="addForm.cropsName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作物类型" :label-width="formLabelWidth">
          <el-select v-model="addForm.cropsType" placeholder="请选择作物类型">
            <el-option v-for="t in types" :label="t.dictLabel" :value="t.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="肥料名称" :label-width="formLabelWidth">
          <el-input v-model="addForm.fertilizerName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="种植方式" :label-width="formLabelWidth">
          <el-select v-model="addForm.plantMode" placeholder="请选择种植方式">
            <el-option v-for="t in zzfs" :label="t.dictLabel" :value="t.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="种植年度" :label-width="formLabelWidth">
          <el-input v-model="addForm.year" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否套袋" :label-width="formLabelWidth">
          <el-select v-model="addForm.baggingStatus" placeholder="请选择是否套袋">
            <el-option v-for="t in td" :label="t.dictLabel" :value="t.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="育苗周期" :label-width="formLabelWidth">
          <el-input v-model="addForm.growSeedlingsCycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="灌溉周期" :label-width="formLabelWidth">
          <el-input v-model="addForm.irrigationCycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="施肥周期" :label-width="formLabelWidth">
          <el-input v-model="addForm.applyFertilizerCycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="除草周期" :label-width="formLabelWidth">
          <el-input v-model="addForm.weedCycle" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth">
          <el-input v-model="addForm.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="addForm.remarks" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </div>
    </el-dialog>





    <!-- 作物详情 -->
    <el-dialog center title="农作物链上数据详情" :visible.sync="cropsDetaiDialog" width="700px" append-to-body>
      <el-row>
        <el-col :span="12">农作物ID：{{ cropsDetails.crops_id }}</el-col>
        <el-col :span="12">农作物名称：{{ cropsDetails.crops_name }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">地址：{{ cropsDetails.address }}</el-col>
        <el-col :span="12">农户：{{ cropsDetails.farmer_name }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">施肥情况：{{ cropsDetails.apply_fertilizer_cycle }}</el-col>
        <el-col :span="12">种植方式：{{ cropsDetails.plant_mode }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">肥料名称：{{ cropsDetails.fertilizer_name }}</el-col>
        <el-col :span="12">是否套袋种植：{{ cropsDetails.bagging_status }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">农户电话：{{ cropsDetails.farmer_tel }}</el-col>
        <el-col :span="12">种植年度：{{ cropsDetails.year }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">育苗周期：{{ cropsDetails.grow_seedlings_cycle }}</el-col>
        <el-col :span="12">灌溉周期：{{ cropsDetails.irrigation_cycle }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">除草周期：{{ cropsDetails.weed_cycle }}</el-col>
        <el-col :span="12">登记时间：{{ cropsDetails.register_time }}</el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row>
        <el-col :span="12">备注：{{ cropsDetails.remarks }}</el-col>
      </el-row>
    </el-dialog>

    <!--通知运输-->
    <el-dialog title="通知运输" :visible.sync="dialogFormVisible3">
      <el-form :model="tzform">
        <el-form-item label="选择司机" :label-width="formLabelWidth">
          <el-select v-model="tzform.userName" placeholder="请选择活动区域">
            <el-option v-for="t in sj" :label="t.nickName" :value="t.userName"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="原料厂商" :label-width="formLabelWidth">
          <el-select v-model="tzform.factoryId" placeholder="请选择">
            <el-option v-for="t in cs" :label="t.deptName" :value="t.deptId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="tzform.remarks" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addys">确 定</el-button>
      </div>
    </el-dialog>


    <!--    周期记录-->
    <el-dialog title="记录作物生长情况" :visible.sync="dialogFormVisible4">
      <el-form :model="recordForm">
        <el-row>
          <el-col :span="24" align="center">{{ cropsName }}</el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="温度">
              <el-input v-model="recordForm.temperature" placeholder="请输入温度"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生长情况">
              <el-input v-model="recordForm.growStatus" placeholder="请输入生长情况"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="水分">
              <el-input v-model="recordForm.waterContent" placeholder="请输入水分"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="光照情况">
              <el-input v-model="recordForm.illuminationStatus" placeholder="请输入光照情况"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="内容">
              <el-input v-model="recordForm.remarks" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>
        <el-row>
          <el-col :span="12">
            <el-form-item label="生长图片:">
              <el-upload class="avatar-uploader" :on-change="getFile" :show-file-list="false" :auto-upload="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddrecordFrom">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 过程详情 -->
    <el-drawer size="80%" :visible.sync="dialogFormVisible5" :show-close="false" :with-header="false">
      <el-divider content-position="left">农作物链上过程详情</el-divider>
      <el-table v-loading="loading" :data="cropsProcessDetailsArray">
        <el-table-column label="过程ID" prop="crops_grow_id"/>
        <el-table-column label="作物ID" prop="crops_bak_id"/>
        <el-table-column label="生长状态" prop="grow_status"/>
        <el-table-column label="光照情况" prop="illumination_status"/>
        <el-table-column label="记录时间" prop="record_time"/>
        <el-table-column label="温度" prop="temperature"/>
        <el-table-column label="水分状态" prop="water_content"/>
        <el-table-column label="备注" prop="remarks"/>
        <el-table-column label="图片" class="demo-image__preview">
          <template slot-scope="scope">
            <el-image :preview-src-list="scope.row.crops_grow_photo_url" :src="scope.row.crops_grow_photo_url"
                      style="width: 100px;height: 80px"></el-image>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

  </div>
</template>

<script>
import {formatDate} from "@/utils";

export default {
  name: "FarmersView",
  data() {
    return {
      tzform: {},
      tableData: [],
      dialogFormVisible: false,
      formLabelWidth: '120px',
      addForm: {},
      types: [],
      zzfs: [],
      td: [],
      cropsDetails:'',
      cropsDetaiDialog: false,
      dialogFormVisible3: false,
      dialogFormVisible4: false,
      dialogFormVisible5: false,
      trasportInfo: '',
      cropsName: '',
      recordForm: {},
      cropsProcessDetailsArray: [],
      sj: [],
      cs: [],
      imgBase64: [],
      imageUrl: '',
      cropsPhotoUrl: '',
      upid: '',
      loading:''
    }
  }, methods: {

    AddrecordFrom() {
      const cropsGrowInfo = this.recordForm;
      const cropsGrowArray = [];
      const id = new this.$snowFlakeId().generate();
      cropsGrowArray.push(id);
      cropsGrowArray.push(id);
      cropsGrowArray.push(this.trasportInfo.cropsId);
      cropsGrowArray.push(formatDate(new Date()));
      cropsGrowArray.push(this.cropsPhotoUrl);
      cropsGrowArray.push(cropsGrowInfo.temperature);
      cropsGrowArray.push(cropsGrowInfo.growStatus);
      cropsGrowArray.push(cropsGrowInfo.waterContent);
      cropsGrowArray.push(cropsGrowInfo.illuminationStatus);
      cropsGrowArray.push(cropsGrowInfo.remarks);
      // alert("111")
      this.$httpBlock
          .post(this.$httpUrl + '/farmerapi/recordCropsGrow', {cropsGrowArray: cropsGrowArray})
          .then(res => {
            if (res.status === 200) {
              this.$message.success('数据上链成功');
              this.dialogFormVisible4 = false;
            }
          }).catch(err => {
            this.$message.error('存储异常 ' + err);
          });
    },
    zqlog(row) {
      this.cropsName = row.cropsName
      this.trasportInfo = row;
      this.dialogFormVisible4 = true;
    },



    //删除
    del() {
      if (this.upid == '') {
        this.$message.error("请选择要修改的任务")
      } else {
        this.$confirm("确定要删除任务吗?", "警告", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.get("farmers/farmers/del", {
            params: {
              id: this.upid,
            }
          }).then(res => {
            if (res.data.code == 200) {
              this.$message.success("删除成功");
              this.init();
            } else {
              this.$message.error("删除失败");
            }
          })
        }).catch(function () {

        })
      }
    },
    //获取选中数据的id
    handleSelectionChange(val) {
      this.upid = val.map(v => v.id).join(",");
    },
    addys() {
      // let username = localStorage.getItem("username");
      this.tzform.farmerUserName = "lijie";
      // console.log(this.tzform.farmerUserName)
      this.tzform.cropsId = this.trasportInfo.cropsId;
      this.tzform.time = new Date();
      this.tzform.driverId = this.tzform.userName;
      this.tzform.status = 0;
      this.axios.post("farmers/farmers/addTrasport", this.tzform).then(res => {
        this.$message.success("成功");
        this.dialogFormVisible3 = false;
        this.init();
      })
    },
    tzys(row) {
      this.dialogFormVisible3 = true;
      this.trasportInfo = row;
      this.getsj();
      this.getcs();
    },

    getsj() {
      this.axios.get("farmers/farmers/sj", {params: {id: 112}}).then(res => {
        this.sj = res.data;
      })
    }, getcs() {
      this.axios.get("farmers/farmers/cs", {params: {cs: 119}}).then(res => {
        this.cs = res.data;
      })
    },

    getFile(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.getBase64(file.raw).then(res => {
        this.imgBase64 = res;
        const datas = {
          imageBase64: this.imgBase64
        };
        this.axios.post("farmers/farmers/imageUpload", datas)
            .then(res => {
              this.cropsPhotoUrl = res.data.msg;
              this.$message.success('图片上传成功');
            })
            .catch(err => {
              this.$message.error('图片上传失败');
            });
      });
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        const reader = new FileReader();
        let imgResult = '';
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },


    //过程详情
    ProcesshandleClick(row) {
      this.$httpBlock
          .get(this.$httpUrl + '/farmerapi/queryCropsProcessByCropsId?id=' + row.cropsId)
          .then(res => {
            const array = [];

            for (let i = 0; i < res.data.length; i++) {
              array.push(res.data[i].Record);
            }
            this.cropsProcessDetailsArray = array;
            this.dialogFormVisible5 = true;
          })
          .catch(err => {
          });
    },
    //农作物详情
    handleClick(row) {
      this.$httpBlock.get(this.$httpUrl + '/farmerapi/queryCropsById?id=' + row.cropsId).then(res => {
        // this.$httpBlock.get("farmers/farmers/getzwxq?id=" + row.id).then(res => {
        // console.log(res.data)
        this.cropsDetails = res.data;
        this.cropsDetaiDialog = true;
      })
    },
    add() {
      let username = localStorage.getItem("username");
      this.addForm.username = username;
      const crops = this.addForm;
      const farmerName='李杰'
      const cropsArray = [];
      cropsArray.push(new this.$snowFlakeId().generate());
      cropsArray.push(new this.$snowFlakeId().generate());
      cropsArray.push(this.addForm.cropsName);
      cropsArray.push(this.addForm.address);
      cropsArray.push(farmerName);
      cropsArray.push(this.addForm.fertilizerName);
      cropsArray.push(this.addForm.plantMode);
      cropsArray.push(this.addForm.baggingStatus);
      cropsArray.push(this.addForm.growSeedlingsCycle);
      cropsArray.push(this.addForm.irrigationCycle);
      cropsArray.push(this.addForm.applyFertilizerCycle);
      cropsArray.push(this.addForm.weedCycle);
      cropsArray.push(this.addForm.remarks);
      cropsArray.push(formatDate(new Date()));
      cropsArray.push(this.addForm.year);
      cropsArray.push("18834114795");
      // this.addForm.username='admin';
      this.$httpBlock.post(this.$httpUrl + '/farmerapi/createCrops', {cropsArray: cropsArray}).then(res => {
        console.log(cropsArray)
        if (res.status == 200) {
          this.$message.success('数据上链成功');
          const cropsUSer = {
            username: farmerName,
            cropsId: cropsArray[0],
            cropsName: cropsArray[2],
            status: 0
          };
          this.axios.post("farmers/farmers/saveCrops", cropsUSer).then(res => {
            this.dialogFormVisible = false;
            this.$message.success("上链成功")
            this.init();
          })
        }
      })

    },
    openAdd() {
      this.dialogFormVisible = true;
      this.getType();
      this.getZzfs();
      this.getTd();
    },
    getType() {
      let type = 'crops_type';
      this.axios.get("farmers/farmers/getTypes", {
        params: {
          type: type
        }
      }).then(res => {
        this.types = res.data.list;
      })
    },
    getZzfs() {
      let type = 'crops_plant_type';
      this.axios.get("farmers/farmers/getTypes", {
        params: {
          type: type
        }
      }).then(res => {
        this.zzfs = res.data.list;
      })
    },
    getTd() {
      let type = 'crops_bagging';
      this.axios.get("farmers/farmers/getTypes", {
        params: {
          type: type
        }
      }).then(res => {
        this.td = res.data.list;
      })
    },
    init() {
      this.axios.get("farmers/farmers/list").then(res => {
        this.tableData = res.data.list;
      })
    },
  }, created() {
    this.init()
  }
}
</script>

<style scoped>

</style>